package com.weihan.javautils;

public class DesignUiUtils {
    public static int designCanvasWidth = 750;
    public static int designCanvasHeight = 1334;
    public static float designCanvasInch = 4.7f;
    private static float density = 0.0f;

    public static float getDensity() {
        if (density == 0.0f)
            density = (float) Math.sqrt(designCanvasWidth * designCanvasWidth + designCanvasHeight * designCanvasHeight) / designCanvasInch / 160;
        return density;
    }

    public static int getDpInt(int px) {
        return Math.round(px / getDensity());
    }

    public static float getDpFloat(float px) {
        return px / getDensity();
    }

    public static void printDpDimenResources(int[] pxs) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n");
        for (int px : pxs) {
            //像素值除以density
            String dp = px * 1.0f / getDensity() + "";
            //拼接成资源文件的内容，方便引用
            if (dp.indexOf(".") + 4 < dp.length()) {//保留3位小数
                dp = dp.substring(0, dp.indexOf(".") + 4);
            }
            stringBuilder.append("<dimen name=\"px").append(px).append("dp\">").append(dp).append("dp</dimen>\n");
        }
        stringBuilder.append("</resources>");
        System.out.println(stringBuilder.toString());
    }

}